package cn.itmantzy.org.controller;

import cn.itmantzy.basic.util.AjaxResult;
import cn.itmantzy.basic.util.PageList;
import cn.itmantzy.org.domain.Department;
import cn.itmantzy.org.query.DepartmentQuery;
import cn.itmantzy.org.service.IDepartmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/dept")
@Api(tags = "部门接口",description = "部门接口详细描述")
// @GetMapping
// @PostMapping
// @PutMapping
// @DeleteMapping
// @PatchMapping
public class DepartmentController {

    @Autowired
    private IDepartmentService departmentService;

    // 新增或修改 Post
    @PostMapping("/addOrUpdate")
    @ApiOperation(value = "部门添加或修改",notes = "如果有id就是修改否则就是添加")
    public AjaxResult addOrUpdate(@RequestBody Department department){
        try {
            if (department.getId() == null){
                departmentService.add(department);
            }else{
                departmentService.update(department);
            }
            return AjaxResult.getAjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.getAjaxResult()
                    .setSuccess(false)
                    .setMessage("系统繁忙，请稍后再试!!!");
        }
    }

    // 删除 Delete
    @DeleteMapping("/{id}")
    public AjaxResult removeById(@PathVariable("id") Long id){
        try {
            departmentService.remove(id);
            return AjaxResult.getAjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            /**
             * 链式编程
             */
            return AjaxResult.getAjaxResult()
                    .setSuccess(false)
                    .setMessage("系统繁忙，请稍后再试");
        }
    }

    // 根据id查询一条数据 Get
    @GetMapping("/{id}")
    public Department findById(@PathVariable("id") Long id){
        return departmentService.queryById(id);
    }

    // 查询所有的数据 Get
    @GetMapping("/list")
    public List<Department> findAll(){
        return departmentService.queryAll();
    }

    // 分页 + 高级查询 Post
    @PostMapping("/page") // 不支持传递对象
    public PageList<Department> findByQuery(@RequestBody DepartmentQuery query){
        return departmentService.queryPage(query);
    }

    // 批量删除
    @PatchMapping
    public AjaxResult removeBatch(@RequestBody Long[] ids){
        try {
            departmentService.removeBatch(ids);
            return AjaxResult.getAjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.getAjaxResult()
                    .setSuccess(false)
                    .setMessage("操作失败，请稍后重试!!!");
        }
    }

    @PostMapping("/tree")
    public List<Department> findOneAndTwoLevelTree(){
        return departmentService.findOneAndTwoLevelTree();
    }

}
